package cn.com.gridinfo.sooc.core.home.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.login.activity.LoginActivity;


/**
 * 引导页轮播View
 */

public class LeadingShowView extends FrameLayout implements View.OnClickListener {

    // 使用universal-image-loader插件读取网络图片，需要工程导入universal-image-loader-1.8.6-with-sources.jar
//	private ImageLoader imageLoader = ImageLoader.getInstance();

    // 轮播图图片数量
    private final static int IMAGE_COUNT = 4;
    // 自动轮播的时间间隔
    private final static int TIME_INTERVAL = 4;
    // 自动轮播启用开关
    private final static boolean isAutoPlay =false;

    // 自定义轮播图的资源
    private int[] imageUrls;

    // 放轮播图片的ImageView 的list
    private List<ImageView> imageViewsList;
    // 放圆点的View的list
    private List<View> dotViewsList;

    private ViewPager viewPager;
    // 当前轮播页
    private int currentItem = 0;
    // 定时任务
    private ScheduledExecutorService scheduledExecutorService;
    private Button lead_ljty_btn;//立即体验按钮
    private Context context;

    //引导页布局
    FrameLayout lead_page_layout;

    //本地存储
    // Handler
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(currentItem);
        }

    };

    public LeadingShowView(Context context) {
        this(context, null);
    }

    public LeadingShowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LeadingShowView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        if (isAutoPlay) {
            startPlay();
        }

    }

    //设置轮播view
    public void setViews(int[] urls, Context context, FrameLayout lead_page_layout) {
        this.imageUrls = urls;
        this.context = context;
        this.lead_page_layout = lead_page_layout;

        initData();
        initUI();
    }


    //初始化数据
    private void initData() {
        imageViewsList = new ArrayList<ImageView>();
        dotViewsList = new ArrayList<View>();
    }


    /**
     * 初始化Views等UI
     */
    private void initUI() {

        //初始化轮播图容器界面
        LayoutInflater.from(context).inflate(R.layout.leading_slideshow, this,
                true);
        //立即体验按钮
        lead_ljty_btn = (Button)findViewById(R.id.lead_ljty_btn);
        lead_ljty_btn.setVisibility(INVISIBLE);
        lead_ljty_btn.setOnClickListener(this);
        //热点
        LinearLayout dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
        dotLayout.removeAllViews();

               // 热点个数与图片特殊相等
        for (int i = 0; i < imageUrls.length; i++) {
            ImageView view = new ImageView(context);
            view.setImageResource(imageUrls[i]);

            view.setScaleType(ScaleType.FIT_XY);
            imageViewsList.add(view);

            ImageView dotView = new ImageView(context);
            if (i == 0) {
                dotView.setBackgroundResource(R.mipmap.dot_focus);
            } else {
                dotView.setBackgroundResource(R.mipmap.dot_blur);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.leftMargin = 4;
            params.rightMargin = 4;
            dotLayout.addView(dotView, params);
            dotViewsList.add(dotView);
        }

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPager.setFocusable(true);

        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener() {

        });
        try {


            Field mScroller;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            Interpolator sInterpolator = new AccelerateInterpolator();
            Scroller scroller = new Scroller(

                    viewPager.getContext(), sInterpolator);
            mScroller.set(viewPager, scroller);


        } catch (NoSuchFieldException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
        viewPager.setCurrentItem(0);

    }

    //点击体验按钮
    @Override
    public void onClick(View view) {
        Log.i("立即体验");
        Arad.preferences.putBoolean(LocalMark.IS_FIRST_APP.getName(), false);
        Arad.preferences.flush();
        //跳转home 页面
        Intent i = new Intent(context, LoginActivity.class);
        context.startActivity(i);
        ((Activity)context).finish();
        AnimUtil.intentSlidIn((Activity)context);
    }

    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        //2秒后开始执行,6秒执行一次
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 2, 6,
                TimeUnit.SECONDS);
    }


    /**
     * 填充ViewPager的页面适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public void destroyItem(View container, int position, Object object) {

            // ((ViewPag.er)container).removeView((View)object);
            ((ViewPager) container).removeView(imageViewsList.get(position));
        }

        @Override
        public Object instantiateItem(View container, final int position) {


            ((ViewPager) container).addView(imageViewsList.get(position));

            return imageViewsList.get(position);
        }

        @Override
        public int getCount() {
            return imageViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

        @Override
        public void finishUpdate(View arg0) {

        }

    }

    /**
     * ViewPager的监听器 当ViewPager中页面的状态发生改变时调用
     */
    private class MyPageChangeListener implements OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
//                    if (viewPager.getCurrentItem() == viewPager.getAdapter()
//                            .getCount() - 1 && !isAutoPlay) {
//                        viewPager.setCurrentItem(0);
//                    }
//                    // 当前为第一张，此时从左向右滑，则切换到最后一张
//                    else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
//                        viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);
//
//                    }
                    break;
            }
        }


        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int pos) {
            currentItem = pos;
            for (int i = 0; i < dotViewsList.size(); i++) {

                if (i == pos) {
                    ((View) dotViewsList.get(pos))
                            .setBackgroundResource(R.mipmap.dot_focus);
                } else {
                    ((View) dotViewsList.get(i))
                            .setBackgroundResource(R.mipmap.dot_blur);
                }
            }
            //页面换到最后一张的时候，显示立即体验按钮
            if(pos == (dotViewsList.size()-1)){
                lead_ljty_btn.setVisibility(View.VISIBLE);
            }else{
                lead_ljty_btn.setVisibility(View.INVISIBLE);
            }
        }

    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {

        @Override
        public void run() {
            synchronized (viewPager) {
                currentItem = (currentItem + 1) % imageViewsList.size();
                handler.obtainMessage().sendToTarget();
            }
        }

    }

}